package com.bysj.lms.service.impl;

import com.bysj.lms.common.ResultModel;
import com.bysj.lms.pojo.entity.User;
import com.bysj.lms.mapper.UserMapper;
import com.bysj.lms.pojo.vo.UserVo;
import com.bysj.lms.service.IRoleUserService;
import com.bysj.lms.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bysj.lms.utils.EncryptUtil;
import com.bysj.lms.utils.SaltUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.transform.Result;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaojiakai
 * @since 2022-02-04
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IRoleUserService roleUserService;
    /**
     * 通过用户名获取用户信息
     */
    public UserVo getByUsername(String username){

        UserVo userVo = userMapper.getByUsername(username);
        if(userVo!=null){
            List<Integer> roleIds = IntStream.range(0, userVo.getRoles().size())
                    .map(i -> userVo.getRoles().get(i).getId()).boxed().collect(Collectors.toList());
            userVo.setRoleIds(roleIds);
        }
        return userVo;
    }

    @Override
    public PageInfo findByPage(String name,int page, int count) {
        PageHelper.startPage(page,count);
        List<UserVo> users = userMapper.userList(name);
        users.forEach(userVo -> {
            List<Integer> roleIds = IntStream.range(0, userVo.getRoles().size())
                    .map(i -> userVo.getRoles().get(i).getId()).boxed().collect(Collectors.toList());
            userVo.setRoleIds(roleIds);
        });

        return new PageInfo(users);
    }

    @Override
    public void updateLoginTime(String id) {
        lambdaUpdate().eq(User::getId,id)
                .set(User::getLastLoginTime, LocalDateTime.now()).update();
    }

    @Override
    public ResultModel changePwd(String username, String oldPwd, String newPwd) {
        boolean matches = Pattern.matches("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$", newPwd);
        String message = "";
        if (!matches){
            return ResultModel.failure("密码必须包含大小写字母和数字的组合，可以使用特殊字符，长度在8-10之间");
        }else{
            UserVo user = getByUsername(username);
            oldPwd = EncryptUtil.encrypt(oldPwd, user.getSalt());
            if(StringUtils.equals(user.getPassword(),oldPwd)){
                String salt = SaltUtil.getRandomCode(4, 6);
                newPwd = EncryptUtil.encrypt(newPwd,salt);
                boolean update = lambdaUpdate().eq(User::getUsername, username)
                        .set(User::getPassword, newPwd).set(User::getSalt, salt).update();
                return update?ResultModel.success("修改成功"):ResultModel.failure("修改失败");
            }else{
                return ResultModel.failure("旧密码错误");
            }
        }
    }

    @Override
    public boolean delete(String id) {
        boolean update = lambdaUpdate().set(User::getStatus, "1").eq(User::getId, id).update();
        return update;
    }

    @Override
    public boolean edit(UserVo userVo) {
        //修改基本信息
        boolean editUser = updateById(userVo);
        //修改角色
        boolean editRole = roleUserService.edit(userVo.getRoleIds(), userVo.getId());
        return editUser && editRole;

    }

    @Override
    public boolean add(UserVo userVo) {
        UserVo existUser = getByUsername(userVo.getUsername());
        String salt = SaltUtil.getRandomCode(4, 6);
        String password = EncryptUtil.encrypt("123456", salt);
        if(existUser != null){
            if(existUser.getStatus().equals("1")){
                userVo.setId(existUser.getId());
                userVo.setPassword(password);
                userVo.setSalt(salt);
                userVo.setStatus("0");
                return edit(userVo);
            }else{
                return false;
            }
        }else{
            userVo.setPassword(password);
            userVo.setSalt(salt);
            userVo.setStatus("0");
            boolean save = save(userVo);
            List<Integer> roleIds = userVo.getRoleIds();
            boolean adds = roleUserService.adds(roleIds, userVo.getId());
            return save && adds;
        }
    }
}
